package kiven.jee.utils.common;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("rawtypes")
public class ReflectionUtil {
	private static Logger logger = LoggerFactory.getLogger(ReflectionUtil.class);
	
	private ReflectionUtil() {}
	
	/**
	 * 通过反射，获得定义Class时声明的父类泛型参数类型.如public UserDao extends HibernateDao<User>
	 * @param clazz 声明的Class
	 * @return 返回父类的泛型类型
	 */
	public static Class getSuperClassGenricType(final Class clazz) {
		return getSuperClassGenricType(clazz,0);
	}

	/**
	 * 通过反射，获得定义Class时声明的父类的泛型参数类型.
	 *  如public UserDao extends HibernateDao<User,Long...>
	 *  
	 * @param clazz 声明的Class 
	 * @param i 要获得父类泛型类型，根据index获得相应位置的泛型
	 * @return
	 */
	private static Class getSuperClassGenricType(final Class clazz, final int index) {
		Type genType = clazz.getGenericSuperclass();
		
		if (! (genType instanceof ParameterizedType)) {
			logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
			return Object.class;
		}
		
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		
		if (index >= params.length || index < 0) {
			logger.warn("Index: " + index + ", Size of "
					+ clazz.getSimpleName() + "'s ParameterizedType Type: "
					+ params.length);
			return Object.class;
		}
		
		return (Class) params[index];
	}
}
